package com.tf_cut.backend.seller.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.mapper.SellerProjectMapper;
import com.tf_cut.backend.payment.service.PaymentService;
import com.tf_cut.backend.platform.vo.RechargeVo;
import com.tf_cut.backend.seller.pojo.ProvideDetail;
import com.tf_cut.backend.seller.service.SellerAccountDetailService;
import com.tf_cut.backend.seller.service.SellerAccountService;
import com.tf_cut.backend.seller.service.SellerOrderService;
import com.tf_cut.backend.seller.vo.SellerAccountDetailVo;
import com.tf_cut.backend.seller.vo.SellerOrderVo;
import com.tf_cut.backend.seller.vo.SellerProjectPersonVo;
import com.tf_cut.backend.util.ConfigSettingUtil;
import com.tf_cut.backend.util.OrderPaymentQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/backend/seller/order")
@Slf4j
public class SellerOrderController {
	private Logger logger = LogManager.getLogger(SellerOrderController.class);

	@Resource
	private ConfigSettingUtil configUtil;
	@Autowired
	private SellerOrderService sellerOrderService;
	@Autowired
	private SellerAccountService sellerAccountService;
	@Autowired
	private SellerAccountDetailService sellerAccountDetailService;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private SellerProjectMapper sellerProjectMapper;
	// 获取商户订单
	@RequestMapping("get")
    public String get( String id) {
		Result<SellerOrderVo> result = sellerOrderService.get(id);
		return JSON.toJSONString(result.getData(),SerializerFeature.WriteDateUseDateFormat);
    }
	
	// 查找商户订单清单（带分页）
	@RequestMapping("findListSellerOrder")
	public String findListSeller(String json) {
		SellerOrderVo avo = JSON.parseObject(json, SellerOrderVo.class);
		return JSON.toJSONString(sellerOrderService.findListSellerOrder(avo),SerializerFeature.WriteDateUseDateFormat);
	}
	
	
	@RequestMapping("findByProjectInfo")
	public List<SellerOrderVo> findByProjectInfo(@RequestParam("orderId") String orderId){
		
		return sellerOrderService.findByProjectInfo(orderId);
	}
	
	@PostMapping("importOrder")
	public String importSeller(String json) {
		return JSON.toJSONString(sellerOrderService.insertSellers(json));
	}

	@PostMapping("/updateDetailPaymentStatus")
	public Result<String> updateDetailPaymentStatus(String json){
		ProvideDetail avo = JSON.parseObject(json, ProvideDetail.class);
		sellerOrderService.updateDetailPaymentStatus(avo.getPaymentStatus(),avo.getId());
		Result<String> result = Result.of("修改成功");
		return result;
	}

	@PostMapping("/update")
	public Result<String> updatePlatformGrant(@RequestBody SellerOrderVo sellerOrderVo) {
		Result<String> result = Result.of("修改成功");
		try {
			SellerOrderVo svo = SellerOrderVo.builder().orderId(sellerOrderVo.getOrderId()).build();

			SellerOrderVo sor = sellerOrderService.findSellerOrder(sellerOrderVo);

			//如果原订单ID状态不为0，禁止再次操作
			if(sor.getApproveStatus() != 3){
				logger.info("订单号：" + sor.getOrderId() + "已经审核完成！");
				result.setMsg("请勿重复操作。");
				result.setFlag(false);
				result.setData("操作失败");
				return result;
			}

			if(2 == sellerOrderVo.getApproveStatus()){
			/*	//取消审核【方法记录不通过的情况下生成退款订单】02   的收入记录
                SellerOrderVo retSellerOrder = sellerOrderService.findSellerOrder(svo);
                SellerAndAccountVo sellerAndAccountVo = SellerAndAccountVo.builder().sellerId(retSellerOrder.getSellerId()).build();
                SellerAndAccountVo retSellerAndAccountVo = sellerAccountService.findSellerAccountByCondition(sellerAndAccountVo);
                generateSellerAccountDetail(retSellerOrder,1,"02","0003",retSellerAndAccountVo.getSellerAccountId(),"发放退款");*/
				sellerOrderVo.setOrderType(2);
				//改变任务状态
				SellerProjectPersonVo projectvo=new SellerProjectPersonVo();
				projectvo.setSellerId(sellerOrderVo.getOrderId());//订单号
				projectvo.setStatus(2);//取消
				sellerProjectMapper.updateStart(projectvo);
            }
			sellerOrderService.updateSellerOrder(sellerOrderVo);

			if(sellerOrderVo.getApproveStatus() == 1){
				String isPayment = configUtil.getConfigValue("payment","is_payment");    //支付开关

				//标记该笔订单下的详情支付通道 【N：线下支付  O：线上支付】
				if(isPayment.equals("off")){
					sellerOrderService.updateDetailPaymentStatusByOrderId("N",sellerOrderVo.getOrderId());
				}else if(isPayment.equals("on")){
					sellerOrderService.updateDetailPaymentStatusByOrderId("O",sellerOrderVo.getOrderId());
					//如果是线上支付，将该发放订单加入支付队列中
					logger.info("发放订单："+sellerOrderVo.getOrderId()+"当前线上支付，加入支付队列等待对其所有明细进行支付.");
					OrderPaymentQueue.set(sellerOrderVo.getOrderId());
				}

				//改变任务状态
				SellerProjectPersonVo projectvo=new SellerProjectPersonVo();
				projectvo.setSellerId(sellerOrderVo.getOrderId());//订单号
				projectvo.setStatus(3);//成功
				sellerProjectMapper.updateStart(projectvo);
				//原来审核通过加费用清单明细
			/*	SellerOrderVo retSellerOrder = sellerOrderService.findSellerOrder(svo);
                SellerAndAccountVo sellerAndAccountVo = SellerAndAccountVo.builder().sellerId(retSellerOrder.getSellerId()).build();
                SellerAndAccountVo retSellerAndAccountVo = sellerAccountService.findSellerAccountByCondition(sellerAndAccountVo);
                generateSellerAccountDetail(retSellerOrder,-1,"00","0003",retSellerAndAccountVo.getSellerAccountId(),"发放支出");*/

			/*
				//使用支付队列自动发起支付
				//审核通过即发起支付请求
				int res = paymentService.paymentSellerProvide(sellerOrderVo.getOrderId());
				if(res == 0) {
					result.setMsg("付款请求已提交银行处理中...");
					result.setFlag(true);
					result.setData("请求成功");

				}else if(res == 1){
					result.setMsg("银行处理超时");
					result.setFlag(false);
					result.setData("请求失败");
				}else if(res == 9){
					//支付通道没有开启
				}
			 */
				result.setMsg("付款请求已提交银行处理中...");
				result.setFlag(true);
				result.setData("请求成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("updatePlatformGrant error:{}", e.getMessage(), e);
			result.setMsg("更新发放状态失败");
			result.setFlag(false);
			result.setData("修改失败");
		}
		return result;
	}

	/**
	 * 失败交易，插入到明细表，对冲成功明细
	 * @param retSellerOrder
	 * @param operType -1支出 1收入
	 * @param orderSource
	 * @param paySubject
	 */
	private void generateSellerAccountDetail(SellerOrderVo retSellerOrder,int operType,String orderSource, String paySubject,String sellerAccountId,String msg) {
		Timestamp now = Timestamp.valueOf(LocalDateTime.now());
		SellerAccountDetailVo sellerAccountDetailVo = new SellerAccountDetailVo();
		sellerAccountDetailVo.setSellerId(retSellerOrder.getSellerId());
		sellerAccountDetailVo.setSellerAccountId(sellerAccountId);
		sellerAccountDetailVo.setTradeSerial(retSellerOrder.getOrderId());
		sellerAccountDetailVo.setServiceId(retSellerOrder.getServiceId());
		sellerAccountDetailVo.setOrderSource(orderSource);
		sellerAccountDetailVo.setOperType(operType);
		sellerAccountDetailVo.setPayTime(now);
		sellerAccountDetailVo.setPaySubject(paySubject);
		sellerAccountDetailVo.setPayType(1);
		sellerAccountDetailVo.setTradeMoney(retSellerOrder.getRealAmount());
		sellerAccountDetailVo.setIsTotal("N");
		sellerAccountDetailVo.setTradeComment(msg);
		sellerAccountDetailVo.setTotalTime(now);
//		sellerAccountDetailVo.setCpmTime(now);
		sellerAccountDetailService.save(sellerAccountDetailVo);
	}
}
